/*
 * @(#)SynThreadPoolExecutor.java   1.0  2022年4月1日
 * 
 * Copyright (c)	2014-2020. All Rights Reserved.	GuangZhou hhmk Technology Company LTD.
 */
package com.swift.core.thread;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 阻塞线程池
 * 
 * @author zhengjiajin
 * @version 1.0 2022年4月1日
 */
public class SynThreadPoolExecutor {
    private static Logger log = LoggerFactory.getLogger(SynThreadPoolExecutor.class);

    private ThreadPoolExecutor executorService;

    private LinkedBlockingQueue<Runnable> queue;

    public SynThreadPoolExecutor(int min, int max,int queueNum) {
        queue = new LinkedBlockingQueue<Runnable>(queueNum);
        executorService = new ThreadPoolExecutor(min, max, 60L, TimeUnit.SECONDS, queue);
        executorService.setRejectedExecutionHandler(new ExecutionHandler());
    }

    public void execute(Runnable command) {
        executorService.execute(command);
    }

    private class ExecutionHandler implements RejectedExecutionHandler {

        /**
         * @see java.util.concurrent.RejectedExecutionHandler#rejectedExecution(java.lang.Runnable,
         *      java.util.concurrent.ThreadPoolExecutor)
         */
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            try {
                queue.put(r);
            } catch (InterruptedException e) {
                log.error("put queue error ", e);
            }
        }

    }
}
